package com.xliee.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xliee.modules.sys.entity.UserEntity;
import com.xliee.modules.sys.mapper.UserMapper;
import com.xliee.modules.sys.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.catalina.util.StringUtil;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lisongsong@xliee.com
 * @since 2024-08-27 14:34:11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements IUserService {

    @Override
    public String doLogin(UserEntity user, HttpServletRequest request) {
        if(StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())){
            return "用户名和密码不能为空";
        }
        UserEntity userEntity = this.baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("user_name", user.getUserName()));
        if(userEntity == null){
            return "用户名密码错误";
        }
        if(user.getPassword().equals(userEntity.getPassword())){
            //让旧的session失效
            HttpSession sessionOld = request.getSession(false);
            if(sessionOld != null){
                sessionOld.invalidate();
            }
            //重新生成session
            HttpSession sessionNew = request.getSession(true);
            sessionNew.setAttribute("ConstantUtil.SESSION_KEY", userEntity);
            return "success";
        }else {
            return "用户名密码错误";
        }
    }

    @Override
    public int logout(HttpServletRequest request) {
        request.getSession().removeAttribute("ConstantUtil.SESSION_KEY");
        return 1;
    }
}
